package com.hy.admin.service.impl;

import java.io.IOException;
import java.util.*;

import com.hy.admin.dao.*;
import com.hy.admin.entity.*;
import com.hy.admin.enums.*;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.hy.admin.helper.request.ASRRequest;
import com.hy.admin.helper.response.ASRResponse;
import com.hy.admin.helper.response.ContentResponse;
import com.hy.admin.helper.response.CourseIntroResponse;
import com.hy.admin.helper.response.CourseResponse;
import com.hy.admin.helper.response.HomeResponse;
import com.hy.admin.helper.response.OrderResponse;
import com.hy.admin.service.CourseService;
import com.hy.admin.service.MessageService;
import com.hy.core.response.ServicesResult;
import com.hy.thread.AddMessageThread;
import com.hy.thread.QueryTranslateThread;
import com.hy.thread.ThreadPoolService;
import com.hy.thread.TranslateFailThread;
import com.hy.thread.UpdateContentThread;
import com.hy.utils.ASRUtil;
import com.hy.utils.CommonUtility;
import com.hy.utils.OSSUtil;

/**
 * Created by yangqq on 18/4/4.
 */
@Service
public class CourseServiceImpl implements CourseService {
    protected final Logger logBase = LoggerFactory.getLogger(CourseServiceImpl.class);
    @Autowired
    private CourseDao courseDao;
    @Autowired
    private CourseOrderDao courseOrderDao;
    @Autowired
    private MemberDao memberDao;
    @Autowired
    private MemberIncomeDao memberIncomeDao;
    @Autowired
    private MemberIncomeDetailDao memberIncomeDetailDao;
    @Autowired
    private ImageDao imageDao;
    @Autowired
    private CourseTranslateFailLogDao logDao;

    @Autowired
    private MessageService messageService;
    @Autowired
    private CourseTranslateFailLogDao courseTranslateFailLogDao;
    @Autowired
    private FreeCourseTypeDao freeCourseTypeDao;
    @Autowired
    private NewsDao newsDao;

    @Override
    public ServicesResult<HomeResponse> homeCourse() {
        ServicesResult<HomeResponse> servicesResult = new ServicesResult<>();

        //查询免费课程
        List<CourseInfoEntity> freeCourseList = courseDao.selectForFree();

        //查询精品课
        List<CourseInfoEntity> greatCourseList = courseDao.selectForGreat();

        //查询新闻
        List<NewsEntity> newsList = newsDao.selectByIsRecommend();

        //返回名师简介---写死数据
        List<TeacherInfoEntity> teacherInfoList = new ArrayList<>();
        TeacherInfoEntity teacherInfo = new TeacherInfoEntity();
        teacherInfo.setImgPath("http://hy-pic.oss-cn-shenzhen.aliyuncs.com/file/3E7693716F0043FC8C5F8C5B77E45F19.jpg");
        teacherInfo.setIntroduce("马小朋老师，北京好氧家校共育文化科技有限公司创始人，中国家校共育指导导师，具有多年家校共育经验");
        teacherInfoList.add(teacherInfo);


        //处理返回数据
        HomeResponse homeResponse = new HomeResponse();
        homeResponse.setFreeCourse(freeCourseList);
        homeResponse.setGreatCourse(greatCourseList);
        homeResponse.setTeacherInfos(teacherInfoList);
        homeResponse.setNews(newsList);
        servicesResult.setResult(homeResponse);
        return servicesResult;
    }

    @Override
    public ServicesResult<List<CourseInfoEntity>> allCourse(Integer pageNum, Integer pageSize) {
        ServicesResult<List<CourseInfoEntity>> servicesResult = new ServicesResult<>();
        //查询课程
        //设置分页条件，Parameters:pageNum 页码pageSize 每页显示数量count 是否进行count查询
        if(pageNum == null || pageNum <= 0){
            //初始页码为1
            pageNum = 1;
        }
        if(pageSize == null || pageSize <= 0){
            //初始数量为20
            pageSize = 20;
        }
        PageHelper.startPage(pageNum, pageSize);
        List<CourseInfoEntity> courseList = courseDao.selectAll();
        servicesResult.setResult(courseList);
        return servicesResult;
    }

    @Override
    public ServicesResult<List<CourseInfoEntity>> listByMemberBuy(Long memberId,Integer pageNum,Integer pageSize){
        ServicesResult<List<CourseInfoEntity>> servicesResult = new ServicesResult<>();
        //校验请求参数
        if (memberId == null || memberId < 0){
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("请求报文有误");
            return servicesResult;
        }
        //查询课程
        //设置分页条件，Parameters:pageNum 页码pageSize 每页显示数量count 是否进行count查询
        if(pageNum == null || pageNum <= 0){
            //初始页码为1
            pageNum = 1;
        }
        if(pageSize == null || pageSize <= 0){
            //初始数量为20
            pageSize = 20;
        }
        PageHelper.startPage(pageNum, pageSize);
        List<CourseInfoEntity> courseList = courseOrderDao.selectCourseByMemberId(memberId);

        servicesResult.setResult(courseList);
        return servicesResult;
    }

    @Override
    public ServicesResult<List<CourseResponse>> listByMemberId(Long memberId,Integer pageNum,Integer pageSize){
        ServicesResult<List<CourseResponse>> servicesResult = new ServicesResult<>();
        //校验请求参数
        if (memberId == null || memberId < 0){
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("请求报文有误");
            return servicesResult;
        }
        //查询教师的所有课程
        //设置分页条件，Parameters:pageNum 页码pageSize 每页显示数量count 是否进行count查询
        if(pageNum == null || pageNum <= 0){
            //初始页码为1
            pageNum = 1;
        }
        if(pageSize == null || pageSize <= 0){
            //初始数量为20
            pageSize = 20;
        }
        PageHelper.startPage(pageNum, pageSize);
        List<CourseResponse> courseList = courseDao.selectByMemberId(memberId);
        servicesResult.setResult(courseList);
        return servicesResult;
    }

    @Override
    public ServicesResult<List<CourseInfoEntity>> listBySeriesId(Long seriesId) {
        ServicesResult<List<CourseInfoEntity>> servicesResult = new ServicesResult<>();
        //校验请求参数
        if (seriesId == null || seriesId < 0){
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("请求报文有误");
            return servicesResult;
        }
        List<CourseInfoEntity> courseList = courseDao.selectCourseBySeriesId(seriesId);
        servicesResult.setResult(courseList);
        return servicesResult;
    }

    @Override
    public ServicesResult<List<CourseInfoEntity>> search(String keyword) {
        ServicesResult<List<CourseInfoEntity>> servicesResult = new ServicesResult<>();
        //校验请求参数
        if (StringUtils.isBlank(keyword)){
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("请求报文有误");
            return servicesResult;
        }
        //查询教师的所有课程
        List<CourseInfoEntity> courseList = courseDao.selectCourseByKeyword(keyword);
        servicesResult.setResult(courseList);
        return servicesResult;
    }

    @Override
    public ServicesResult<CourseResponse> detail(Long id, Long memberId){
        ServicesResult<CourseResponse> servicesResult = new ServicesResult<>();
        //校验请求参数
        if (id == null || id < 0){
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("请求报文有误");
            return servicesResult;
        }
        //查询课程详情
        CourseResponse courseResponse = courseDao.selectById(id);
        //查询课程是否被购买
        courseResponse.setIsBuy(false);
        if(memberId != null && memberId > 0){
            int count = courseOrderDao.selectPaidCountByMIdAndCId(memberId, id, EnumPayState.PAID.getId());
            courseResponse.setIsBuy(count > 0);
        }
        servicesResult.setResult(courseResponse);
        return servicesResult;
    }

    @Override
    public ServicesResult<CourseIntroResponse> introduce(Long id){
        ServicesResult<CourseIntroResponse> servicesResult = new ServicesResult<>();
        //校验请求参数
        if (id == null || id < 0){
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("请求报文有误");
            return servicesResult;
        }
        //查询课程详情
        CourseEntity course = courseDao.selectByPrimaryKey(id);
        //校验请求参数
        if (course == null){
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("请求报文有误");
            return servicesResult;
        }
        //查询教师信息
        MemberEntity member = memberDao.selectById(course.getMemberId());
        if (member == null){
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("请求报文有误");
            return servicesResult;
        }
        CourseIntroResponse ciResponse = new CourseIntroResponse();

        //获取教师图片
        List<String> imageList = imageDao.selectByRelatedIdAndType(course.getMemberId(), EnumImageRelatedType.HEAD_IMAGE.getId());
        if(imageList != null){
            ciResponse.setImgPath(imageList.get(0));
        }
        //处理返回数据
        ciResponse.setNickName(member.getNickName());
        ciResponse.setIndividualitySign(member.getIndividualitySign());
        ciResponse.setCourseDescr(course.getDescr());
        servicesResult.setResult(ciResponse);
        return servicesResult;
    }

    @Override
    public ServicesResult<OrderResponse> buy(Long memberId, Long courseId) {
        ServicesResult<OrderResponse> servicesResult = new ServicesResult<>();
        //校验请求参数
        if (courseId == null || courseId < 0){
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("请求报文有误");
            return servicesResult;
        }
        if (memberId == null || memberId < 0){
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("请求报文有误");
            return servicesResult;
        }
        CourseEntity course = courseDao.selectByPrimaryKey(courseId);
        if(course == null){
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("请求参数有误，课程不存在");
            return servicesResult;
        }
        int count = courseOrderDao.selectPaidCountByMIdAndCId(memberId, courseId, EnumPayState.PAID.getId());
        if(count > 0){
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("课程已经购买，请勿重复购买");
            return servicesResult;
        }
        //创建订单对象
        CourseOrderEntity coEntity = new CourseOrderEntity();

        String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase();

        coEntity.setUuid(uuid);
        coEntity.setCourseId(courseId);
        coEntity.setMemberId(memberId);
        coEntity.setPrice(course.getPrice());
        coEntity.setPayState(EnumPayState.UNPAID.getId());
        Calendar cal = Calendar.getInstance();
        coEntity.setCreateTime(cal.getTime());
        coEntity.setUpdateTime(cal.getTime());
        //插入数据
        int result = courseOrderDao.insertSelective(coEntity);
        if(result <= 0){
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("课程购买失败");
            return servicesResult;
        }
        Long id = courseOrderDao.selectByUuid(uuid);
        OrderResponse orderResponse = new OrderResponse();
        orderResponse.setResult(true);
        orderResponse.setId(id);
        servicesResult.setResult(orderResponse);
        return servicesResult;
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public ServicesResult<Boolean> paySuccess(Long orderId) throws Exception {
        ServicesResult<Boolean> servicesResult = new ServicesResult<>();
        //校验请求参数
        if (orderId == null || orderId < 0){
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("请求报文有误");
            return servicesResult;
        }
        CourseOrderEntity courseOrder = courseOrderDao.selectByPrimaryKey(orderId);
        if(courseOrder == null){
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("请求参数有误，订单不存在");
            return servicesResult;
        }
        //修改订单支付状态
        courseOrder.setPayState(EnumPayState.PAID.getId());
        Calendar cal = Calendar.getInstance();
        Date time = cal.getTime();
        courseOrder.setUpdateTime(time);
        //修改数据
        int result = courseOrderDao.updateByPrimaryKeySelective(courseOrder);
        if(result <= 0){
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("支付状态修改失败");
            return servicesResult;
        }
        //增加教师账户金额
        CourseEntity course = courseDao.selectByPrimaryKey(courseOrder.getCourseId());
        if (course == null) {
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("课程不存在");
            throw new Exception("课程不存在");
        }
        MemberIncomeEntity memberIncome = memberIncomeDao.selectByMemberId(course.getMemberId());
        Double beforePrice = memberIncome == null ? 0d : memberIncome.getAmount();
        if (memberIncome == null) {
            //教师的第一笔收入
            memberIncome = new MemberIncomeEntity();
            memberIncome.setMemberId(course.getMemberId());
            memberIncome.setAmount(courseOrder.getPrice());
            memberIncome.setStatus(EnumStatus.VALID.getId());
            memberIncome.setCreateTime(time);
            memberIncome.setUpdateTime(time);
            result = memberIncomeDao.insertSelective(memberIncome);
        } else {
            memberIncome.setAmount(memberIncome.getAmount() + courseOrder.getPrice());
            memberIncome.setUpdateTime(time);
            result = memberIncomeDao.updateByPrimaryKeySelective(memberIncome);

        }
        if (result <= 0) {
            //如账户金额修改失败则事务回滚
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("账户金额修改失败");
            throw new Exception("账户金额修改失败");
        }
        //插入收入明细表
        MemberIncomeDetailEntity memberIncomeDetail = new MemberIncomeDetailEntity();
        memberIncomeDetail.setBeforePrice(beforePrice);
        memberIncomeDetail.setPrice(courseOrder.getPrice());
        memberIncomeDetail.setIncomeType(0);
        memberIncomeDetail.setMemberId(course.getMemberId());
        memberIncomeDetail.setStatus(EnumStatus.VALID.getId());

        result = memberIncomeDetailDao.insertSelective(memberIncomeDetail);

        if (result <= 0) {
            //如插入收入明细表失败则事务回滚
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("收支明细插入失败");
            throw new Exception("收支明细插入失败");
        }

        servicesResult.setResult(true);
        return servicesResult;
    }

    @Override
    public ServicesResult<Boolean> addWithFile(CourseEntity courseEntity, MultipartFile file, MultipartFile image) throws Exception {
        ServicesResult<Boolean> servicesResult = new ServicesResult<>();
        //校验请求参数
        if (courseEntity == null){
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("请求报文有误");
            return servicesResult;
        }
        //校验必传参数
        if (courseEntity.getMemberId() == null){
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("请求参数有误，必传参数为空");
            return servicesResult;
        }
        if (StringUtils.isEmpty(courseEntity.getDescr())){
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("请求参数有误，必传参数为空");
            return servicesResult;
        }
        if (StringUtils.isEmpty(courseEntity.getTitle())){
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("请求参数有误，必传参数为空");
            return servicesResult;
        }
        if (courseEntity.getPrice() == null || courseEntity.getPrice() < 0){
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("请求参数有误，必传参数为空");
            return servicesResult;
        }
        if(file == null){
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("上传文件有误");
            return servicesResult;
        }
        //上传图片至阿里云OSS
        //获取文件名
        String fileType = OSSUtil.getFileType(file.getOriginalFilename());
        if(!"wav".equals(fileType) && !"mp3".equals(fileType)){
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("上传文件格式有误");
            return servicesResult;
        }
        //使用工具类
        String filePath = OSSUtil.uploadFile(CommonUtility.multipartToFile(file), fileType);
        if (filePath == null || StringUtils.isEmpty(filePath)) {
            //图片上传失败
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("文件上传oss失败");
            return servicesResult;
        }
        //存入数据库
        courseEntity.setRadioLink(filePath);

        //处理封面
        if (image != null){
            fileType = OSSUtil.getFileType(image.getOriginalFilename());
            if(!"png".equals(fileType) && !"jpg".equals(fileType)){
                servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
                servicesResult.setStatusMsg("上传文件格式有误");
                return servicesResult;
            }
            //使用工具类
            filePath = OSSUtil.uploadFile(CommonUtility.multipartToFile(image), fileType);
            if (filePath == null || StringUtils.isEmpty(filePath)) {
                //图片上传失败
                servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
                servicesResult.setStatusMsg("文件上传oss失败");
                return servicesResult;
            }
            courseEntity.setFaceImgPath(filePath);
        }

        String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase();
        courseEntity.setUuid(uuid);
        if(courseEntity.getPrice() == 0d){
            courseEntity.setIsFree(EnumIsFree.YES.getId());
        }

        courseEntity.setTranslateState(EnumTranslateState.RUNNING.getId());

        Calendar cal = Calendar.getInstance();

        courseEntity.setCreateTime(cal.getTime());
        courseEntity.setUpdateTime(cal.getTime());
        courseEntity.setStatus(EnumStatus.VALID.getId());
        int count = courseDao.insertSelective(courseEntity);
        if(count <= 0){
            //数据插入失败
            //删除上传的文件
            OSSUtil.deleteFile(filePath);
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("数据库插入失败");
            return servicesResult;
        }
        //语音转文字
        changeToText(uuid, courseEntity.getRadioLink());
        servicesResult.setResult(true);
        return servicesResult;
    }

    @Override
    public ServicesResult<Boolean> add(CourseEntity courseEntity){
        ServicesResult<Boolean> servicesResult = new ServicesResult<>();
        //校验请求参数
        if (courseEntity == null){
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("请求报文有误");
            return servicesResult;
        }
        //校验必传参数
        if (courseEntity.getMemberId() == null){
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("请求参数有误，必传参数为空");
            return servicesResult;
        }
        if (StringUtils.isEmpty(courseEntity.getDescr())){
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("请求参数有误，必传参数为空");
            return servicesResult;
        }
        if (StringUtils.isEmpty(courseEntity.getTitle())){
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("请求参数有误，必传参数为空");
            return servicesResult;
        }
        if (courseEntity.getPrice() == null || courseEntity.getPrice() < 0){
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("请求参数有误，必传参数为空");
            return servicesResult;
        }
        if(StringUtils.isBlank(courseEntity.getRadioLink())){
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("请求参数有误，必传参数为空");
            return servicesResult;
        }
        String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase();
        courseEntity.setUuid(uuid);
        if(courseEntity.getPrice() == 0d){
            courseEntity.setIsFree(EnumIsFree.YES.getId());
        }

        courseEntity.setTranslateState(EnumTranslateState.RUNNING.getId());

        Calendar cal = Calendar.getInstance();

        courseEntity.setCreateTime(cal.getTime());
        courseEntity.setUpdateTime(cal.getTime());
        courseEntity.setStatus(EnumStatus.VALID.getId());
        int count = courseDao.insertSelective(courseEntity);
        if(count <= 0){
            //数据插入失败
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("数据库插入失败");
            return servicesResult;
        }
        //语音转文字
        changeToText(uuid, courseEntity.getRadioLink());
        servicesResult.setResult(true);
        return servicesResult;
    }


    /**
     * 将语音转换为文本
     * @param uuid
     * @param filePath
     */
    private void changeToText(String uuid, String filePath){

        //调用阿里云ASR转语音为文字
        ASRRequest asrRequest = new ASRRequest();
        asrRequest.setApp_key("nls-service-multi-domain");
        asrRequest.setOss_link(filePath);
        String body = JSON.toJSONString(asrRequest);
        ASRResponse response = ASRUtil.sendPost(body);

        if (response.getStatus() == 200) {
            String taskId = JSON.parseObject(response.getResult()).getString("id");
            //查询转换结果
            String status = queryTranResult(taskId, uuid);
            if("RUNNING".equals(status)) {
                //创建查询线程
                ThreadPoolService.addThreadToCommonPool(new QueryTranslateThread(taskId, uuid));
            }
        }
    }

    /**
     * 通过TaskId获取识别结果
     * @param taskId
     * @param uuid
     * @return
     */
    @Override
    public String queryTranResult(String taskId, String uuid){
        ASRResponse response = ASRUtil.sendGet(taskId);
        String status = JSON.parseObject(response.getResult()).getString("status");
        if(status.equals("SUCCEED")){
            String result = JSON.parseObject(response.getResult()).getString("result");
            List<String> resultArr = JSON.parseArray(result, String.class);
            StringBuilder sb = new StringBuilder();
            for(String jString : resultArr){
                Integer channelId = Integer.parseInt(JSON.parseObject(jString).getString("channel_id"));
                if(channelId == 0) {
                    sb.append(JSON.parseObject(jString).getString("text"));
                }
            }
            String text = sb.toString();
            logBase.info("queryTranResult.result:" + result + ",text:" + text);
            int count = updateContent(uuid, text);
            if(count <= 0){
                //写入数据失败，调用线程继续写入
                ThreadPoolService.addThreadToCommonPool(new UpdateContentThread(uuid, text));
            }
        }else if(status.equals("FAILED")){
            //记录转换失败记录
            int count = addTranslateFailLog(uuid);
            if(count <= 0){
                ThreadPoolService.addThreadToCommonPool(new TranslateFailThread(uuid));
            }
        }
        return status;
    }

    @Override
    public int addTranslateFailLog(String uuid){
        CourseEntity course = courseDao.selectByUuId(uuid);

        CourseTranslateFailLogEntity logEntity = new CourseTranslateFailLogEntity();
        logEntity.setCourseId(course.getId());
        logEntity.setRadioLink(course.getRadioLink());
        logEntity.setStatus(EnumStatus.VALID.getId());

        Calendar cal = Calendar.getInstance();

        logEntity.setCreateTime(cal.getTime());
        logEntity.setUpdateTime(cal.getTime());

        int count = logDao.insertSelective(logEntity);

        if(count>0) {
            course.setTranslateState(EnumTranslateState.FAIL.getId());
            course.setUpdateTime(new Date());
            count = courseDao.updateByPrimaryKeySelective(course);
        }
//        if(count > 0) {
//            //语音识别失败后给其他用户发送消息
//            //添加用户消息
//            Boolean result = messageService.addMessage(course.getMemberId());
//            if (!result) {
//                //创建线程后续重新插入数据
//                ThreadPoolService.addThreadToCommonPool(new AddMessageThread(course.getMemberId()));
//            }
//        }
        return count;
    }

    /**
     * 保存语音文本
     * @param uuid
     * @param content
     * @return
     */
    @Override
    public int updateContent(String uuid, String content){
        CourseEntity course = courseDao.selectByUuId(uuid);
        course.setContent(content);
        course.setUpdateTime(new Date());
        course.setTranslateState(EnumTranslateState.SUCCESS.getId());
        return courseDao.updateByPrimaryKeySelective(course);
    }

    @Override
    public ServicesResult<Boolean> addClickNum(Long courseId){
        ServicesResult<Boolean> servicesResult = new ServicesResult<>();

        int count = courseDao.updateClickNum(courseId);

        if(count <= 0){
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("数据修改失败");
            return servicesResult;
        }
        servicesResult.setResult(true);
        return servicesResult;
    }

    @Override
    public ServicesResult<Boolean> downloadFile(Long courseId, String localFilePath) {
        ServicesResult<Boolean> servicesResult = new ServicesResult<>();
        //校验请求参数
        if (courseId == null || courseId < 0){
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("请求报文有误");
            return servicesResult;
        }
        if (StringUtils.isBlank(localFilePath)){
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("请求报文有误");
            return servicesResult;
        }
        CourseEntity course = courseDao.selectByPrimaryKey(courseId);
        if(course == null){
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("请求课程不存在");
            return servicesResult;
        }
        String fileType = course.getRadioLink().substring(course.getRadioLink().lastIndexOf("."), course.getRadioLink().length());
        OSSUtil.downloadObject(course.getRadioLink(), localFilePath+"//"+course.getTitle()+fileType);
        servicesResult.setResult(true);
        return servicesResult;
    }

    @Override
    public ServicesResult<ContentResponse> getContent(Long courseId) {
        ServicesResult<ContentResponse> servicesResult = new ServicesResult<>();
        //校验请求参数
        if (courseId == null || courseId <= 0){
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("请求报文有误");
            return servicesResult;
        }
        CourseEntity course = courseDao.selectByPrimaryKey(courseId);
        if(course == null){
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("课程不存在");
            return servicesResult;
        }
        ContentResponse contentResponse = new ContentResponse();
        if(StringUtils.isBlank(course.getContent())){
            int count = courseTranslateFailLogDao.selectByCourseId(courseId);
            if(count > 0){
                contentResponse.setStatus("FAIL");
            }else{
                contentResponse.setStatus("RUNNING");
            }
        }else {
            contentResponse.setStatus("SUCCESS");
            contentResponse.setContent(course.getContent());
        }
        servicesResult.setResult(contentResponse);
        return servicesResult;
    }

    @Override
    public ServicesResult<Boolean> audit(Long courseId, Integer auditStatus) {
        ServicesResult<Boolean> servicesResult = new ServicesResult<>();
        if(courseId == null || courseId <= 0){
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("参数有误");
            return servicesResult;
        }
        if(auditStatus == null){
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("参数有误");
            return servicesResult;
        }
        CourseEntity course = courseDao.selectByPrimaryKey(courseId);
        if(course == null){
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("课程不存在");
            return servicesResult;
        }
        int count = courseDao.updateAuditStatus(courseId, auditStatus);

        if(count <= 0){
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("数据修改失败");
            return servicesResult;
        }
        if(auditStatus == EnumAuditStatus.PASS.getId()
                && StringUtils.isNotBlank(course.getContent())) {
            //语音识别成功后给其他用户发送消息
            //添加用户消息
            messageService.addMessageForCourse(course.getMemberId());
        }
        servicesResult.setResult(true);
        return servicesResult;
    }

    @Override
    public int countByMemberId(Long memberId) {
        return courseDao.selectCountByMemberId(memberId);
    }

    @Override
    public ServicesResult<List<CourseInfoEntity>> freeCourse(String nickName, String title, Integer pageNum, Integer pageSize) {
        ServicesResult<List<CourseInfoEntity>> servicesResult = new ServicesResult<>();
        //设置分页条件，Parameters:pageNum 页码pageSize 每页显示数量count 是否进行count查询
        if(pageNum == null || pageNum <= 0){
            //初始页码为1
            pageNum = 1;
        }
        if(pageSize == null || pageSize <= 0){
            //初始数量为20
            pageSize = 20;
        }
        PageHelper.startPage(pageNum, pageSize);
        List<CourseInfoEntity> list = courseDao.selectAllFreeCourse(StringUtils.isNotBlank(title.trim())?title:null,
                StringUtils.isNotBlank(nickName)?nickName:null);
        servicesResult.setResult(list);
        return servicesResult;
    }

    @Override
    public ServicesResult<List<CourseInfoEntity>> chargeCourse(String nickName, String title, Integer pageNum, Integer pageSize) {
        ServicesResult<List<CourseInfoEntity>> servicesResult = new ServicesResult<>();
        //设置分页条件，Parameters:pageNum 页码pageSize 每页显示数量count 是否进行count查询
        if(pageNum == null || pageNum <= 0){
            //初始页码为1
            pageNum = 1;
        }
        if(pageSize == null || pageSize <= 0){
            //初始数量为20
            pageSize = 20;
        }
        PageHelper.startPage(pageNum, pageSize);
        List<CourseInfoEntity> list = courseDao.selectAllChargeCourse(StringUtils.isNotBlank(title.trim())?title:null,
                StringUtils.isNotBlank(nickName)?nickName:null);
        servicesResult.setResult(list);
        return servicesResult;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ServicesResult<Boolean> setTop(Integer isFree, String ids) throws Exception {
        ServicesResult<Boolean> servicesResult = new ServicesResult<>();
        //校验请求参数
        if (StringUtils.isBlank(ids)){
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("请求报文有误");
            return servicesResult;
        }
        String[] idArr = ids.split(",");
        int max = (isFree == 0 ? 10 : 4);
        int existsCount = courseDao.selectCountForTopAndFree(isFree);
        if((existsCount + idArr.length) > max){
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("置顶课程最多10节");
            return servicesResult;
        }
        //删除原有置顶
//        courseDao.cancelTop(isFree);
        //修改置顶数据
        List<Long> idList = new ArrayList<>();
        for (String id : idArr){
            idList.add(Long.parseLong(id));
        }
        int count = courseDao.setTop(isFree,idList);
        if(count <= 0){
            throw  new Exception("数据修改失败");
        }
        servicesResult.setResult(true);
        return servicesResult;
    }

    @Override
    public ServicesResult<Boolean> cancelTop(String ids) {
        ServicesResult<Boolean> servicesResult = new ServicesResult<>();
        //校验请求参数
        if (StringUtils.isBlank(ids)){
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("请求报文有误");
            return servicesResult;
        }
        String[] idArr = ids.split(",");
        //修改置顶数据
        List<Long> idList = new ArrayList<>();
        for (String id : idArr){
            idList.add(Long.parseLong(id));
        }
        int count = courseDao.cancelTop(idList);
        if(count <= 0){
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("修改失败");
            return servicesResult;
        }
        servicesResult.setResult(true);
        return servicesResult;
    }

    @Override
    public ServicesResult<Boolean> setCourseType(Long id, Integer courseType) {
        ServicesResult<Boolean> servicesResult = new ServicesResult<>();
        if (id == null || id <= 0){
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("请求报文有误");
            return servicesResult;
        }
        CourseEntity course = courseDao.selectByPrimaryKey(id);
        if(course == null){
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("课程不存在");
            return servicesResult;
        }
        if(course.getIsFree() == EnumIsFree.NO.getId()){
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("非免费课程");
            return servicesResult;
        }

        FreeCourseTypeEntity freeCourseType = freeCourseTypeDao.selectByCourseId(id);

        int count = 0;

        if (freeCourseType == null){
            //新增
            freeCourseType = new FreeCourseTypeEntity();
            freeCourseType.setCourseId(id);
            freeCourseType.setCourseType(courseType);
            freeCourseType.setStatus(EnumStatus.VALID.getId());
            freeCourseType.setCreateTime(new Date());
            count = freeCourseTypeDao.insertSelective(freeCourseType);
        }else{
            //修改
            freeCourseType.setCourseType(courseType);
            freeCourseType.setUpdateTime(new Date());
            count = freeCourseTypeDao.updateByPrimaryKeySelective(freeCourseType);
        }
        servicesResult.setResult( count > 0);
        return servicesResult;
    }

    @Override
	public ServicesResult<Boolean> updateContent(Long courseId, String content) {
		ServicesResult<Boolean> result = new ServicesResult<Boolean>();
		if(courseId == null) {
			result.setResult(false);
		}
		else {
			CourseEntity record = new CourseEntity();
			record.setId(courseId);
			record.setContent(content);
			int ret = courseDao.updateByPrimaryKeySelective(record );
			result.setResult(ret > 0);
		}
		return result;
	}

    @Override
    public ServicesResult<Boolean> updatePrice(Long courseId, Double price) {
        ServicesResult<Boolean> result = new ServicesResult<Boolean>();
        if(courseId == null) {
            result.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            result.setStatusMsg("请求报文有误");
            return result;
        }
        CourseEntity course = courseDao.selectByPrimaryKey(courseId);
        if(course == null){
            result.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            result.setStatusMsg("课程不存在");
            return result;
        }
        int isFree = price == 0 ? EnumIsFree.YES.getId() : EnumIsFree.NO.getId();
        if(course.getSetTop() == 1 && course.getIsFree() != isFree){
            //课程属于置顶课程,并且存在免费与收费的转换
            result.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            result.setStatusMsg("课程已置顶，如需修改，请取消置顶后操作");
            return result;
        }
        course.setPrice(price);
        course.setIsFree(isFree);
        int ret = courseDao.updateByPrimaryKeySelective(course);
        result.setResult(ret > 0);
        return result;
    }

	@Override
	public ServicesResult<FreeCourseTypeEntity> getCourseFreeType(Long courseId) {
		if(courseId == null || courseId < 0) {
			return null;
		}
		FreeCourseTypeEntity freeCourseType = freeCourseTypeDao.selectByCourseId(courseId);
		ServicesResult<FreeCourseTypeEntity> result = new ServicesResult<FreeCourseTypeEntity>();
		result.setResult(freeCourseType);
		return result;
	}

    @Override
    public ServicesResult<Boolean> updateFaceImg(Long id, MultipartFile file) throws IOException {
        ServicesResult<Boolean> servicesResult = new ServicesResult<>();
        if( id == null || id <= 0) {
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("请求报文有误");
            return servicesResult;
        }
        if (file == null){
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("请选择文件");
            return servicesResult;
        }
        CourseEntity course = courseDao.selectByPrimaryKey(id);
        if(course == null){
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("课程不存在");
            return servicesResult;
        }
        
        String oldFilePath=course.getFaceImgPath();

        String fileType = OSSUtil.getFileType(file.getOriginalFilename());
        String filePath = OSSUtil.uploadFile(CommonUtility.multipartToFile(file),fileType);
        if(StringUtils.isBlank(filePath)){
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("oss文件上传失败");
            return servicesResult;
        }

        course.setFaceImgPath(filePath);
        course.setUpdateTime(new Date());
        int count = courseDao.updateByPrimaryKeySelective(course);

        if(count <= 0){
            //保存数据失败,删除阿里云文件
            OSSUtil.deleteFile(filePath);
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("数据修改失败");
            return servicesResult;
        }

        //删除旧文件
        if (StringUtils.isNotBlank(course.getFaceImgPath())) {
            OSSUtil.deleteFile(oldFilePath);
        }
        servicesResult.setResult(true);
        return servicesResult;
    }

}
